<template>
  <div
    class="index-container"
    :style="`height:${view.height}px;background:${
      isDark ? '#1B1B1F' : '#fff'
    };`"
  >
    <div class="header-container">
      <div class="header-main">
        <el-menu
          :default-active="'/index/general/algorithmManage/algorithmList'"
          class="el-menu-demo"
          mode="horizontal"
          :ellipsis="false"
          @select="handleSelect"
          router
        >
          <h1 class="logo">
            <el-image
              style="width: 40px; height: 40px"
              :src="logo"
              alt="Element logo"
              fit="scale-down"
            />
            <div class="tit">
              <!-- Subsystem Name Display -->
              <el-text v-if="!isEditing" class="system-name">
                {{ selectedSubsystemName }}
                <el-button
                  type="text"
                  icon="Edit"
                  size="small"
                  @click="startEditing"
                  class="edit-button"
                  v-show="selectedRoleName=='系统管理员'||selectedRoleName=='超级管理员'"
                ></el-button>
              </el-text>

              <!-- Subsystem Name Dropdown -->
              <el-select
                v-else
                v-model="selectedSubsystem"
                placeholder="选择系统"
                @change="onSubsystemChange"
                @blur="stopEditing"
                class="editable-dropdown"
              >
                <el-option
                  v-for="subsystem in subsystems"
                  :key="subsystem.id"
                  :label="subsystem.name"
                  :value="subsystem.id"
                />
              </el-select>
            </div>
          </h1>
          <div class="flex-grow"></div>
          <el-menu-item index="/index/general/algorithmManage/algorithmList"
            >算法管理通用配置</el-menu-item
          >
          <el-menu-item  v-show="selectedRoleName=='系统管理员'||selectedRoleName=='超级管理员'" index="/index/userCenter/userManage/userList"
            >用户中心</el-menu-item
          >

          <el-menu-item  v-show="selectedRoleName=='系统管理员'||selectedRoleName=='超级管理员'" index="/index/dataManageCenter/stationTypeManage/stationTypeList"
            >数据管理</el-menu-item
          >
          <el-menu-item  v-show="selectedRoleName=='系统管理员'||selectedRoleName=='超级管理员'" index="/cutFiles"
            >批量干旱指数计算(自动处理)
          </el-menu-item>
          <el-menu-item  v-show="selectedRoleName=='系统管理员'||selectedRoleName=='超级管理员'" index="/cutFiles2"
            >灌溉面积提取
          </el-menu-item>
          <el-menu-item  v-show="selectedRoleName=='系统管理员'||selectedRoleName=='超级管理员'" index="/index/feedbackCenter/feedbackManage/feedbackList"
            >意见反馈中心
          </el-menu-item>
          <el-menu-item  v-show="selectedRoleName=='系统管理员'||selectedRoleName=='超级管理员'" index="/index/consoleCenter/consoleManage/consoleList"
            >控制台中心
          </el-menu-item>
          <div class="flex-grow"></div>
          <el-menu-item>
            <el-switch style="display: flex;align-items: center;"
              v-model="value1"
              :disabled="false"
              :active-action-icon="Moon"
              :inactive-action-icon="Sunny"
              size="large"
              active-text="黑暗"
              inactive-text="明亮"
              @click="darkModeHandler()"
            />
          </el-menu-item>
          <el-sub-menu index="">
            <template #title>
              <div style="display: flex;align-items: center;">
                <span style="font-size: 14px;"> {{ subsystemStore.getUser.username }},  {{selectedRoleName}}</span>&nbsp;&nbsp;&nbsp;
                <el-avatar :icon="UserFilled" :size="30" />
              </div>
            </template>
            <el-menu-item @click="exitHandler">退出登录</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>
    </div>
    <router-view></router-view>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { Sunny, Moon, UserFilled } from "@element-plus/icons-vue";
import logo from "@/assets/logo/logo.png";
import { ElMessage } from "element-plus";
import HttpService from "@/api/api";
import router from "@/router";
import { useSubsystemStore } from "@/store/subsystem";
import { useDark, useToggle } from "@vueuse/core";

let isDark = ref(useDark());
let value1 = ref(useDark());
const toggleDark = useToggle(isDark);

// Subsystem-related data
const subsystemStore = useSubsystemStore();
const subsystems = ref([]); // List of subsystems
const Roles = ref([]); // List of subsystems
const selectedSubsystemName = ref(); // Currently selected subsystem name
const selectedSubsystem = ref(subsystemStore.getSubsystem);
const selectedRoleName = ref(); // Currently selected subsystem name
const selectedRole = ref(subsystemStore.getRole);
const isEditing = ref(false); // Editing state for the subsystem name
const subsystemPagination = reactive({
  page_index: 1,
  page_size: 10,
  page_total: 0,
});
const tableLoading = ref(false);

// Fetch subsystems
const getSubsystems = () => {
  const params = {
    limit: subsystemPagination.page_size,
    page: subsystemPagination.page_index,
  };
  tableLoading.value = true;
  HttpService.subsystemManage.subsystemList(
    params,
    (res) => {
      if (res.status === 200) {
        subsystems.value = res.data.data;
        subsystems.value.forEach(subsystem=>{
            if(subsystem.id==subsystemStore.getSubsystem){
                selectedSubsystemName.value=subsystem.name
            }
        })
        subsystemPagination.page_total = res.data.total;
      } else {
        ElMessage.error("获取子系统列表失败");
      }
      tableLoading.value = false;
    },
    (error) => {
      ElMessage.error("请求失败，请稍后重试");
      tableLoading.value = false;
    }
  );
};
const rolePagination = reactive({
    page_index: 1,
    page_size: 30,
    page_total: 0,
  });
  // 获取角色列表
  const getRoles = () => {
    const params = {
      limit: rolePagination.page_size,
      page: rolePagination.page_index,
    };
    tableLoading.value = true;
    HttpService.roleManage.roleList(
      params,
      (res) => {
        if (res.status === 200) {
            Roles.value = res.data.data;
            console.log(Roles.value)
            Roles.value.forEach(role=>{
                if(selectedRole.value==role.id){
                    selectedRoleName.value = role.name
                }
            })
         
        } else {
          ElMessage.error("获取角色列表失败");
        }
        tableLoading.value = false;
      },
      (error) => {
        ElMessage.error("请求失败，请稍后重试");
        tableLoading.value = false;
      }
    );
  };

// Start editing system name
const startEditing = () => {
  isEditing.value = true;
};

// Stop editing system name
const stopEditing = () => {
  isEditing.value = false;
  const selected = subsystems.value.find(
    (s) => s.id === selectedSubsystem.value
  );
  if (selected) {
    selectedSubsystemName.value = selected.name;
    subsystemStore.setSubsystem(selectedSubsystem.value);
    console.log(subsystemStore.getSubsystem)
    ElMessage.success(`系统已切换为：${selected.name}`);
  }
};

// Handle subsystem selection
const onSubsystemChange = (subsystemId: string) => {
  subsystemStore.setSubsystem(subsystemId);
  stopEditing();
};

// Other methods
const handleSelect = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

const darkModeHandler = () => {
  toggleDark();
};

const exitHandler = () => {
  router.push("/login");
};

// Fetch subsystems on mount
onMounted(() => {
  getSubsystems();
  getRoles()
});

const view = reactive({
  height: window.innerHeight,
});

window.addEventListener("resize", () => {
  view.height = window.innerHeight;
});
</script>

<style lang="scss" scoped>
.flex-grow {
  flex-grow: 1;
}

.index-container {
  transition: all 1s;
}

.header-container {
  display: flex;
  justify-content: center;

  .header-main {
    width: 100%;
    min-width: 1482px;
    padding: 0 20px;

    .logo {
      display: flex;
      align-items: center;

      .tit {
        margin-left: 20px;
        font-size: 20px;
        font-weight: 500;

        .system-name {
          display: inline-flex;
          align-items: center;
          font-size: 20px;
          font-weight: 600;
          .edit-button {
            margin-left: 8px;
            font-size: 14px;
          }
        }

        .editable-dropdown {
          width: 200px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.el-switch{
    line-height:20px;
}
</style>
